package com.shuai.robot.service.impl;


import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.shuai.common.constant.*;
import com.shuai.common.dto.SessionChatRecordDTO;
import com.shuai.common.exception.BusinessException;
import com.shuai.common.service.user.InnerSessionChatRecordService;
import com.shuai.common.service.user.InnerSessionService;
import com.shuai.common.service.user.InnerUserService;
import com.shuai.robot.dto.ChatModelReq;
import com.shuai.robot.dto.ChatModelRps;
import com.shuai.robot.dto.UserDTO;
import com.shuai.robot.service.AIInteractService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;

@Service
@Slf4j
public class AIInteractServiceImpl implements AIInteractService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private WebClient webClient;

    @DubboReference
    private InnerSessionChatRecordService sessionChatRecordService;

    @DubboReference
    private InnerSessionService innerSessionService;

    @DubboReference
    private InnerUserService innerUserService;


    @Value("${xs-robot.api-key}")
    private String apiKey;
    @Value("${xs-robot.api-secret}")
    private String apiSecret;
    @Value("${xs-robot.version}")
    private String version;


    @Override
    public ChatModelRps interactAskOnce(String question, String userId) {
        // 根据用户ID查询用户信息
        String userJson = stringRedisTemplate.opsForValue().get(UserConstant.USER_ATTRIBUTE_REDIS_KEY + userId);
        UserDTO userInfo = JSONUtil.toBean(userJson, UserDTO.class);
        // 拿到用户类型，填充每次请求的token数量
        Integer level = userInfo.getLevel();
//        UserLevelTokenRelatedEnum tokenRpsLimit = UserLevelTokenRelatedEnum.getById(level); // 根据用户等级获取模型回复token的上限
        String authSuffix = apiKey + ":" + apiSecret;
        if (CharSequenceUtil.isNotBlank(userInfo.getApiKey())
                && CharSequenceUtil.isNotBlank(userInfo.getApiSecret())) {
            authSuffix = userInfo.getApiKey() + ":" + userInfo.getApiSecret();
        }
        // 请求讯飞星火模型，拿到响应结果
        HashMap<String, String> header = new HashMap<>();
        header.put(AuthenticationConstant.AUTHENTICATION_HEADER, "Bearer " + authSuffix);
        header.put("Content-Type", "application/json");
        ChatModelReq chatModelReq = ChatModelReq.builder()
                .model(version)
//                .max_tokens(tokenRpsLimit.getTokens())
                .messages(
                        Collections.singletonList(ChatModelReq.
                                Message
                                .builder()
                                .role(ConversationRoleEnum.USER.getRole()).
                                content(question)
                                .build()))
                .build();
        HttpResponse execute = HttpRequest.post(XfSparkRobotConstant.HOST + XfSparkRobotConstant.URI)
                .addHeaders(header)
                .body(JSONUtil.toJsonStr(chatModelReq))
                .execute();
        if (!execute.isOk()) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "网络异常");
        }
        String rpsString = execute.body();
        ChatModelRps chatModelRps = JSONUtil.toBean(rpsString, ChatModelRps.class);
        if (chatModelRps == null || chatModelRps.getCode() != 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "模型响应异常");
        }
        // 扣减用户token
        innerUserService.decreaseUserToken(chatModelRps.getUsage().getTotal_tokens(), userId);
        // 返回模型响应结果
        return chatModelRps;
    }


    @Override
    public long addSessionDefault(String sessionName, String userId) {
        return innerSessionService.addUserSessionDefault(sessionName, userId);
    }

    @Override
    public void saveSessionBatch(List<SessionChatRecordDTO> sessionChatRecordDTOList) {
        sessionChatRecordService.saveSessionChatRecordBatch(sessionChatRecordDTOList);
    }

    @Override
    public void decreaseTokenCount(int usedTokenCount, String userId) {
        innerUserService.decreaseUserToken(usedTokenCount, userId);
    }
}
